import { useState, useEffect } from 'react'
import { View, Text, Image } from '@tarojs/components'
import Taro, { useDidShow } from '@tarojs/taro'
import './index.scss'
import avatarPng from '../../resource/user.png'
import billPng from '../../resource/qkuang.png'
import statsPng from '../../resource/tubiao.png'
import settingsPng from '../../resource/user.png'
import helpPng from '../../resource/noqkuang.png'
import contactPng from '../../resource/nojiz.png'

interface UserInfo {
  avatar: string
  nickname: string
  phone: string
  level: string
}

interface MenuItem {
  icon: string
  title: string
  desc: string
  path: string
}

const User = () => {
  const [userInfo, setUserInfo] = useState<UserInfo>({
    avatar: avatarPng,
    nickname: '家伟',
    phone: '138****8888',
    level: 'VIP会员'
  })

  const [systemInfo, setSystemInfo] = useState({
    windowHeight: 0,
    windowWidth: 0,
    pixelRatio: 1,
    platform: ''
  })

  // 主题：light | dark
  const [theme, setTheme] = useState<'light' | 'dark'>(() => {
    try {
      const cached = Taro.getStorageSync('app_theme') as 'light' | 'dark'
      return cached === 'dark' ? 'dark' : 'light'
    } catch {
      return 'light'
    }
  })

  const menuItems: MenuItem[] = [
    {
      icon: billPng,
      title: '我的账单',
      desc: '查看所有账单记录',
      path: '/pages/overview/index'
    },
    {
      icon: statsPng,
      title: '数据统计',
      desc: '收支分析报告',
      path: '/pages/discover/index'
    },
    {
      icon: settingsPng,
      title: '设置',
      desc: '个人设置与偏好',
      path: ''
    },
    {
      icon: helpPng,
      title: '帮助中心',
      desc: '使用帮助与反馈',
      path: ''
    },
    {
      icon: contactPng,
      title: '联系我们',
      desc: '客服与技术支持',
      path: ''
    }
  ]

  // 获取系统信息
  useEffect(() => {
    const getInfo = async () => {
      try {
        const res = await Taro.getSystemInfo()
        setSystemInfo({
          windowHeight: res.windowHeight,
          windowWidth: res.windowWidth,
          pixelRatio: res.pixelRatio,
          platform: res.platform || ''
        })
      } catch (err) {
        console.error('获取系统信息失败:', err)
      }
    }
    
    getInfo()
  }, [])

  // 同步主题到本地存储
  useEffect(() => {
    try {
      Taro.setStorageSync('app_theme', theme)
    } catch {}
  }, [theme])

  // 页面显示时刷新数据
  useDidShow(() => {
    // 可以在这里刷新用户信息
  })

  const handleMenuClick = async (item: MenuItem) => {
    if (item.path) {
      const tabPaths = new Set([
        '/pages/index/index',
        '/pages/overview/index',
        '/pages/discover/index',
        '/pages/user/index',
      ])
      if (tabPaths.has(item.path)) {
        Taro.switchTab({ url: item.path })
      } else {
        Taro.navigateTo({ url: item.path })
      }
      return
    }
    if (item.title === '设置') {
      try {
        const res = await Taro.showActionSheet({
          itemList: ['浅色主题', '深色主题'],
        })
        const next = res.tapIndex === 1 ? 'dark' : 'light'
        setTheme(next)
        Taro.showToast({
          title: next === 'dark' ? '已切换为深色主题' : '已切换为浅色主题',
          icon: 'none'
        })
      } catch (e) {
        // 用户取消
      }
      return
    }

    if(item.title === '联系我们') {
      Taro.navigateTo({ url: '/pages/user/customerServiceChat/index' })
      return
    }
    Taro.showToast({
      title: `${item.title}功能开发中`,
      icon: 'none'
    })
  }

  const handleEditProfile = () => {
    Taro.showModal({
      title: '编辑资料',
      content: '此功能正在开发中，敬请期待！',
      showCancel: false,
      confirmText: '知道了'
    })
  }

  return (
    <View className={`user-page ${theme === 'dark' ? 'theme-dark' : 'theme-light'}`}>
      {/* 用户信息头部 */}
      <View className="user-header">
        <View className="user-info">
          <Image className="avatar" src={userInfo.avatar} />
          <View className="user-details">
            <Text className="nickname">{userInfo.nickname}</Text>
            <Text className="phone">{userInfo.phone}</Text>
            <View className="level-badge">
              <Text className="level-text">{userInfo.level}</Text>
            </View>
          </View>
        </View>
        <View className="edit-btn" onClick={handleEditProfile}>
          编辑
        </View>
      </View>

      {/* 功能菜单 */}
      <View className="menu-section">
        {menuItems.map((item, index) => (
          <View 
            key={index} 
            className="menu-item"
            onClick={() => handleMenuClick(item)}
          >
            <View className="menu-icon">
              <Image className="icon-img" src={item.icon} />
            </View>
            <View className="menu-content">
              <Text className="menu-title">{item.title}</Text>
              <Text className="menu-desc">{item.desc}</Text>
            </View>
            <View className="menu-arrow">
              <Text className="arrow">›</Text>
            </View>
          </View>
        ))}
      </View>

      {/* 底部信息 */}
      <View className="footer-info">
        <Text className="version">版本 v1.0.0</Text>
        <Text className="copyright">© 2024 家伟的快捷记账</Text>
      </View>
    </View>
  )
}

export default User